import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL || '/api', // 从环境变量获取 API URL
  timeout: 15000 // 请求超时时间
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从 localStorage 获取 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Token ${token}`
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    console.log('Response:', response)
    return response.data
  },
  error => {
    console.error('Response error:', error)
    
    // 处理认证错误
    if (error.response?.status === 401) {
      ElMessage({
        message: '请先登录',
        type: 'warning',
        duration: 5 * 1000
      })
      // 清除 token 并跳转到登录页
      localStorage.removeItem('token')
      router.push('/login')
      return Promise.reject(error)
    }
    
    // 处理其他错误
    ElMessage({
      message: error.response?.data?.msg || error.message || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request
